package com.enjoyor.soa.traffic.rest.tsms.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.enjoyor.soa.traffic.api.dto.tsms.TemplateDto;
import com.enjoyor.soa.traffic.frame.annotation.Auth;
import com.enjoyor.soa.traffic.frame.security.bean.dto.UserDto;
import com.enjoyor.soa.traffic.rest.tsms.dubbo.ITemplateConsumeService;
import com.enjoyor.soa.traffic.util.exception.RestException;
import com.enjoyor.soa.traffic.util.pojo.Page;
import com.enjoyor.soa.traffic.util.pojo.ResultPojo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;

import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Auth
@RestController
@RequestMapping({ "/api/template" })
@Api("TemplateController相关api")
@CrossOrigin
public class TemplateExampleController {


    @Autowired
    private ITemplateConsumeService templateConsumeService;
    
    @Autowired
    private com.enjoyor.soa.traffic.rest.tsms.dubbo.invoke.UbmsInfoServiceInvoke ubmsDeptBayonetServiceInvoke;

    @GetMapping(value = { "/select" }, produces = { "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation("根据id查询操作记录")
    @ApiImplicitParam(name = "id", value = "编号", defaultValue = "", paramType = "query", required = true, dataType = "String")
    public ResultPojo select(
    		@RequestParam(defaultValue = "",value="id",required=true) String id, 
    		HttpServletRequest request) {
        return templateConsumeService.select(id);
    }
    /**
	 * 获取模板列表信息
	 * @param id
	 * @param type
	 * @param content
	 * @return
	 */
	@GetMapping(value = { "selectList" }, produces = { "application/json; charset=UTF-8" })
	@ResponseBody
	@ApiResponse(response=TemplateDto.class, code = 0, message = "")
    @ApiOperation("模板列表信息查询")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = "id", value = "编号", paramType = "query", dataType = "String"),
    	@ApiImplicitParam(name = "type", value = "类型", paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "content", value = "内容", paramType = "query", dataType = "String") })
	public ResultPojo getTemplateInfoList(
			@RequestParam(defaultValue = "",value="id",required=false) String id,
			@RequestParam(defaultValue = "",value="type",required=false) String type,
			@RequestParam(defaultValue = "",value="content",required=false) String content,
			/*@RequestParam(value="startTime",required=false) Date startTime,*/
			HttpServletRequest request) {
		return templateConsumeService.selectList(id, type, content);
	}
    @SuppressWarnings({ "rawtypes" })
    @GetMapping(value = { "/selectPage" }, produces = { "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "timeStart", value = "开始时间", paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "timeEnd", value = "结束时间", paramType = "query", dataType = "String")})
    public ResultPojo selectPage(
    		@RequestParam(defaultValue = "",value="timeStart",required=false) String timeStart,
			@RequestParam(defaultValue = "",value="timeEnd",required=false) String timeEnd,
    		Page page, HttpServletRequest request) {
        return templateConsumeService.selectPage(page, timeStart, timeEnd);
    }

    @PostMapping(value = { "/create" }, consumes = { "application/json; charset=UTF-8" }, produces = {
            "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation("创建数据")
    public ResultPojo create(@RequestBody TemplateDto templateDto, HttpServletRequest request) {
        return templateConsumeService.insert(templateDto,
                ((UserDto) request.getAttribute("currentUser")).getPersonName());
    }

    @PutMapping(value = { "/update" }, consumes = { "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation("更新数据")
    public ResultPojo update(@RequestBody TemplateDto templateDto, HttpServletRequest request) {
        return templateConsumeService.edit(templateDto,
                ((UserDto) request.getAttribute("currentUser")).getPersonName());
    }

    @DeleteMapping(value = { "/delete" }, produces = { "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation("删除数据")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query", required = true, dataType = "String")
    public ResultPojo delete(@PathVariable("id") String id, HttpServletRequest request) {
        return templateConsumeService.delete(id, ((UserDto) request.getAttribute("currentUser")).getPersonName());
    }

    @GetMapping(value = { "/selectCurrentUser" }, produces = { "application/json; charset=UTF-8" })
    @ResponseBody
    public ResultPojo selectCurrentUser(HttpServletRequest request) {
        return new ResultPojo(request.getAttribute("currentUser"));
    }

    @PostMapping(value = { "/checkToken" }, consumes = { "application/json; charset=UTF-8" }, produces = {
            "application/json; charset=UTF-8" })
    @ResponseBody
    public ResultPojo checkToken(@RequestParam(value = "token", required = true) String token,
            @RequestParam(value = "sysKey", required = true) String sysKey) {
        return templateConsumeService.check(token, sysKey);
    }

   /* @GetMapping(value = { "/redisGet/{key}" }, produces = { "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation(value = "根据key查询redis具体值", notes = "根据key查询redis具体值")
    @ApiImplicitParam(name = "key", value = "redis-key", paramType = "path", required = true, dataType = "String")
    public ResultPojo redisGet(@PathVariable("key") String key) {
        return new ResultPojo(redisTool.get(key));
    }

    @PostMapping(value = { "/redisSet" }, consumes = { "application/json; charset=UTF-8" }, produces = {
            "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation("创建redis数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "key", defaultValue = "test", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "value", value = "value", defaultValue = "hello", paramType = "query", dataType = "string") })
    public ResultPojo redisSet(@RequestParam(value = "key", required = true) String key,
            @RequestParam(value = "value", required = true) String value) {
        redisTool.set(key, value);
        return new ResultPojo();
    }*/

    @PostMapping(value = { "/exception" }, consumes = { "application/json; charset=UTF-8" }, produces = {
            "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation("异常测试")
    public ResultPojo exception(@RequestParam(value = "key", required = true) String key) {
        if (key.equals("1"))
            throw new RestException("tiom.rest.template.example");
        return new ResultPojo();
    }

    @GetMapping(value = { "/callBackTest/{listenId}" }, produces = { "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation(value = "callBackTest", notes = "callBackTest")
    @ApiImplicitParam(name = "listenId", value = "listenId", paramType = "path", required = true, dataType = "String")
    public ResultPojo callBackTest(@PathVariable("listenId") String listenId) {
        return new ResultPojo(templateConsumeService.callback(listenId));
    }

    @GetMapping(value = { "/exportWord" }, produces = { "application/json; charset=UTF-8" })
    @ResponseBody
    @ApiOperation(value = "exportWord", notes = "exportWord")
    public void exportWord(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            //word内容
            //File fileDir = new File(path);
            String content="<html><body><p class=\"ql-align-justify\">\t<strong>李维昊给我留下深刻的印象。</strong></p><p class=\"ql-align-justify\">\t<em>我们班上有位同学叫李维昊</em>，<u>她有一双明亮的眼睛，一张长长的脸，还有一条辫子。</u></p><pre class=\"ql-syntax ql-align-justify\" spellcheck=\"false\">\t她的同桌贺挺，数学成绩很不理想。无奈，数学老师只好把教贺挺这个艰巨的任务交给李维昊。\n" +
                    "</pre><ol><li class=\"ql-align-justify\">\t我们每次都为她着急，但她却不急，她耐心教：乘法，小数乘法，分数乘法。直到满意为止。</li></ol><ul><li class=\"ql-align-justify\">\t一次次，贺挺面对着复杂的数学公式和<span style=\"color: rgb(240, 102, 102);\">成堆的数学题，都会摇摇头放弃。但李维昊并不生气，只是一遍又一遍的教着贺挺，没抱怨一句。为了让贺挺快点进步，他不辞辛苦，拿出宝贵的课余时间来教贺挺。</span></li></ul><p class=\"ql-align-justify ql-indent-1\"><span style=\"background-color: rgb(230, 0, 0);\">\t别人一次次的说她不值得：“花出宝贵的时间教贺挺这个笨蛋。”她却</span>一言不发，默默的教贺挺。贺挺在李维昊的教导下，越来越进步。</p><p class=\"ql-direction-rtl ql-align-center\">\t贺挺<span class=\"ql-size-huge\">能有今天，多</span>亏了李维昊。我们应该学习李维昊的乐于助人的精神。</p><p><br></p></body></html>";
            byte b[] = content.getBytes("utf-8");  //这里是必须要设置编码的，不然导出中文就会乱码。
            ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
            /*
             * 关键地方
             * 生成word格式 */
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            DocumentEntry documentEntry = directory.createDocument("文档名称", bais);
            //输出文件
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String( (documentEntry.getName() + ".doc").getBytes(),  "utf-8"));
            OutputStream ostream = response.getOutputStream();
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.close();
        }catch(Exception e){
            //异常处理
        }
    }

}
